package com.purchase.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.persistence.Transient;

import org.apache.commons.lang3.StringUtils;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.purchase.entity.ActivityGoods;
import com.purchase.entity.Brand;
import com.purchase.entity.Goods;
import com.purchase.entity.GoodsImage;
import com.purchase.entity.GoodsStock;
import com.purchase.entity.StoreActivity;
import com.purchase.mapper.ActivityGoodsMapper;
import com.purchase.mapper.BrandMapper;
import com.purchase.mapper.GoodsImageMapper;
import com.purchase.mapper.GoodsMapper;
import com.purchase.mapper.GoodsStockMapper;
import com.purchase.mapper.StoreActivityMapper;
import com.purchase.service.GoodsService;
import com.purchase.util.DateUtil;
import com.purchase.util.EventTag;
import com.purchase.util.LogInfo;
import com.purchase.util.MQUtil;
import com.purchase.util.MyBeanUtils;
import com.purchase.util.RequestForm;
import com.purchase.util.ResponseForm;
import com.purchase.util.Utils;

import lombok.extern.slf4j.Slf4j;

import static java.util.stream.Collectors.groupingBy;

@Slf4j
@Service
public class GoodsServiceImpl implements GoodsService {

	@Resource
	GoodsMapper goodsMapper;

	@Resource
	GoodsImageMapper goodsImageMapper;

	@Resource
	GoodsStockMapper goodsStockMapper;

	@Resource
	BrandMapper brandMapper;

	@Resource
	JmsTemplate jmsTemplate;

	@Resource
	Destination topicDestination;

	@Resource
	StoreActivityMapper storeActivityMapper;

	@Resource
	ActivityGoodsMapper activityGoodsMapper;

	// //商品信息发生变化 调用
	// goodsMapper.conditionCount(paramMap);
	// return null;

	@Override
	public ResponseForm rateCondition(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			String storeNo = (String) paramMap.get("storeNo");
			if (!StringUtils.isNotBlank(storeNo)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			List<Map<String, Object>> list = goodsMapper.rateCondition(paramMap);
			result.setData(list);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			e.printStackTrace();
			log.error(LogInfo.ERROR);
		}
		return result;

	}

	@Override
	public ResponseForm sizeCondition(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			String storeNo = (String) paramMap.get("storeNo");
			if (!StringUtils.isNotBlank(storeNo)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			List<Map<String, Object>> list = goodsMapper.sizeCondition(paramMap);
			result.setData(list);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			e.printStackTrace();
			log.error(LogInfo.ERROR);
		}
		return result;
	}

	@Override
	public ResponseForm getStockGoodsList(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			String storeNo = (String) paramMap.get("storeNo");
			String condition = (String) paramMap.get("condition");
			String orderby = (String) paramMap.get("orderby");
			if (!StringUtils.isNotBlank(storeNo) || !StringUtils.isNotBlank(condition)
					|| !StringUtils.isNotBlank(orderby)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}
			com.purchase.util.Page.parsePage(paramMap);
			Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
			List<Map<String, Object>> list = goodsMapper.getStockGoodsList(paramMap);

			this.addRelationColorToGoodsList(list);

			result.setData(list);
			result.setTotal((int) pageHelper.getTotal());
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			e.printStackTrace();
			log.error(LogInfo.ERROR);
		}
		return result;
	}

	/**
	 * 添加同规格颜色
	 * @param list
	 */
	private void addRelationColorToGoodsList(List<Map<String, Object>> list) {
		if (list.size() > 0) {
			List<Object> relation = list.parallelStream().map((Map<String, Object> c) -> c.get("relation")).collect(Collectors.toList());
			List<Map<String, Object>> stockGoodsListRelationColor = goodsMapper.getStockGoodsListRelationColor(relation);
			Map<Object, List<Map<String, Object>>> collect = stockGoodsListRelationColor.parallelStream().collect(groupingBy((Map<String, Object> c) -> c.get("relation")));
			for (Map<String, Object> goodsMap : list) {
                List<Map<String, Object>> relation1 = collect.get(goodsMap.get("relation"));
                StringBuffer buf = new StringBuffer();
                for (Map<String, Object> stringObjectMap : relation1) {
                    buf.append(stringObjectMap.get("goods_color"));
                    buf.append(",");
                }
                if (buf.length() > 0) {
                    buf.deleteCharAt(buf.length()-1);
                }
                goodsMap.put("relationColor", buf);
            }
		}
	}

	@Override
	public ResponseForm getGoodsById(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			String goodsId = (String) paramMap.get("goodsId");
			String storeNo = (String) paramMap.get("storeNo");
			// Integer userStatus = (Integer) paramMap.get("userStatus");
			// MemberBenefit memBenefit = memBenefitMapper.selectByPrimaryKey(userStatus);
			// String memDiscount = memBenefit.getMemDiscount();

			if (!StringUtils.isNotBlank(goodsId) || !StringUtils.isNotBlank(storeNo)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			Goods goods = goodsMapper.selectByPrimaryKey(Integer.valueOf(goodsId));
			// 品牌信息
			Brand brand = null;
			if (goods.getBrandId() != null)
				brand = brandMapper.selectByPrimaryKey(goods.getBrandId());
			if (brand != null)
				goods.setBrandName(brand.getName());

			// 商品活动信息
			ActivityGoods activityGoods = new ActivityGoods();
			activityGoods.setGoodsId(Integer.valueOf(goodsId));
			activityGoods = activityGoodsMapper.selectOne(activityGoods);
			if (null != activityGoods) {
				StoreActivity storeActivity = new StoreActivity();
				storeActivity.setId(activityGoods.getActivityId());
				storeActivity = storeActivityMapper.selectOne(storeActivity);
				goods.setActivityStatus(storeActivity.getStatus());
				goods.setActivityId(storeActivity.getId());
				goods.setStartTime(storeActivity.getStartTime());
				goods.setEndTime(storeActivity.getEndTime());
			}

			// 处理商品图片
			GoodsImage goodsImage = new GoodsImage();
			goodsImage.setGoodsId(Integer.valueOf(goodsId));
			List<GoodsImage> goodsImageList = goodsImageMapper.select(goodsImage);
			goods.setGoodsImages(goodsImageList);
			// 商品颜色
			List<Map<String, Object>> goodsColour = null;
			String relation = goods.getRelation();
			if (relation != null && !"".equals(relation)) {
				Map<String, Object> relationMap = new HashMap<String, Object>();
				relationMap.put("storeNo", storeNo);
				relationMap.put("relation", relation);
				goodsColour = goodsMapper.getGoodsColourList(relationMap);
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("goods_name", goods.getGoodsName());
				map.put("goods_code", goods.getGoodsCode());
				map.put("goods_color", goods.getGoodsColor());
				map.put("goods_id", goods.getGoodsId());
				map.put("soldout", goods.getSoldout());
				goodsColour = new ArrayList<Map<String, Object>>();
				goodsColour.add(map);
			}
			goods.setGoodsColour(goodsColour);
			// 商品尺寸
			GoodsStock goodsStock = new GoodsStock();
			goodsStock.setGoodsId(Integer.valueOf(goodsId));
			List<GoodsStock> goodsStockList = goodsStockMapper.select(goodsStock);
			goods.setGoodsStock(goodsStockList);

			// /*会员价格计算*/
			// //会员权益和价格
			// if(StringUtils.isNotBlank(memDiscount)) {
			// goods.setMemDiscount(memDiscount);
			// if(goods.getDiscountPrice()!=null) {
			// goods.setMemPrice(memPrice(memDiscount, goods.getDiscountPrice()));
			// }else{
			// goods.setMemPrice(memPrice(memDiscount, goods.getGoodsPrice()));
			// }
			// }

			result.setData(goods);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			e.printStackTrace();
			log.error(LogInfo.ERROR);
		}
		return result;
	}


	@SuppressWarnings({ "unused", "rawtypes" })
	@Override
	public ResponseForm getGoodsByRelation(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if (param.getData() != null) {
			Map paramMap = (Map) param.getData();
			String relation = (String) paramMap.get("relation");
			try {
				/*获取商品基本信息*/
				Goods goods = new Goods();
				goods.setRelation(relation);
				List<Goods> goodsList = goodsMapper.getGoodsByRelation(paramMap);
				if(goodsList==null) {
					result.fail("400", "商品不存在");
				}
				/*循环获取图片和规格,库存信息*/
				for (Goods goodsPojo : goodsList) {
					/*获取轮播图片url,逗号分隔的字符串*/
					String goodsImageUrl = goodsImageMapper.getGoodsImageUrl(goodsPojo.getGoodsId());
					goodsPojo.setGoodsImageUrl(goodsImageUrl);
					/*获取尺寸库存信息*/
					GoodsStock goodsStock = new GoodsStock();
					goodsStock.setGoodsId(goodsPojo.getGoodsId());
					goodsPojo.setGoodsStock(goodsStockMapper.select(goodsStock));
				}
				result.succ("获取数据成功", goodsList);
			} catch (Exception e) {
				e.printStackTrace();
				log.error("数据库访问错误" + e);
				result.fail("400", "数据库访问错误");
			}
		} else {
			result.fail("400", "参数为空");
		}
		return result;
	}

	// /**
	// * @desc 会员折扣价计算
	// * @param memDiscount
	// * @param goodsPrice
	// * @return
	// */
	// @SuppressWarnings("unused")
	// private BigDecimal memPrice(Object memDiscount,Object goodsPrice) {
	// BigDecimal rate = new BigDecimal(memDiscount.toString()).divide(new
	// BigDecimal("10"));
	// BigDecimal price = new BigDecimal(goodsPrice.toString());
	// return price.multiply(rate).setScale(2, BigDecimal.ROUND_HALF_UP);
	// }

	@Transactional(rollbackFor = Exception.class)
	@Override
	public ResponseForm addGoods(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			String storeNo = (String) paramMap.get("storeNo");
			String memberPrice = (String) paramMap.get("memberPrice");
			String memberRate = (String) paramMap.get("memberRate");
			String activityId = (String) paramMap.get("activityId");
			List paramList = (List) paramMap.get("paramList");
			if (!StringUtils.isNotBlank(storeNo) || !StringUtils.isNotBlank(activityId) || paramList == null) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}
			// 原价
			String goodsPrice = (String) paramMap.get("goodsPrice");
			BigDecimal bd = new BigDecimal(goodsPrice);
			paramMap.put("goodsPrice", bd);
			// 折扣价
			String discountPrice = (String) paramMap.get("discountPrice");
			if (StringUtils.isNotBlank(discountPrice)) {
				BigDecimal discountbd = new BigDecimal(discountPrice);
				paramMap.put("discountPrice", discountbd);
			}
			// else{
			// paramMap.put("discountPrice", 0);
			// }
			// 会员价
			if (StringUtils.isNotBlank(memberPrice)) {
				paramMap.put("memberRate", new BigDecimal(memberRate));
				paramMap.put("memberPrice", new BigDecimal(memberPrice));
			}

			// 代购费
			String purchaseCost = (String) paramMap.get("purchaseCost");
			if (StringUtils.isNotBlank(purchaseCost)) {
				BigDecimal cost = new BigDecimal(purchaseCost);
				paramMap.put("purchaseCost", cost);
			} else {
				paramMap.put("purchaseCost", 15);
			}

			// String relation="";
			// 同款不同色商品关系字段
			// if(paramList.size()>1){
			String relation = String.valueOf(System.currentTimeMillis());
			// }

			for (int i = 0; i < paramList.size(); i++) {
				Goods goods = new Goods();
				MyBeanUtils.populate(goods, paramMap);
				goods.setRelation(relation);
				Map<String, Object> map = (Map<String, Object>) paramList.get(i);
				goods.setGoodsColor((String) map.get("goodsColour"));
				goods.setGoodsCode((String) map.get("goodsCode"));
				goods.setSoldonTime(new Date());

				List imgList = (List) map.get("goodsImg");
				// if(imgList!=null && imgList.size()>0)
				// goods.setGoodsPic((String)imgList.get(0));
				goodsMapper.insertSelective(goods);
				if (imgList.size() > 0) {
					GoodsImage gImg;
					for (int j = 0; j < imgList.size(); j++) {
						gImg = new GoodsImage();
						gImg.setGoodsId(goods.getGoodsId());
						gImg.setUrl((String) imgList.get(j));
						gImg.setMediaType(0);
						goodsImageMapper.insertSelective(gImg);
					}
				}
				List sizeList = (List) map.get("goodsSize");
				if (sizeList.size() > 0) {
					GoodsStock gStock;
					for (int k = 0; k < sizeList.size(); k++) {
						Map<String, Object> stockMap = (Map<String, Object>) sizeList.get(k);
						gStock = new GoodsStock();
						gStock.setGoodsId(goods.getGoodsId());
						gStock.setSpecsName((String) stockMap.get("size"));
						String num = (String) stockMap.get("num");
						gStock.setStockNum(Integer.valueOf(num));
						goodsStockMapper.insertSelective(gStock);
					}
				}
				// 商品关联活动
				ActivityGoods activityGoods = new ActivityGoods();
				activityGoods.setGoodsId(goods.getGoodsId());
				activityGoods.setActivityId(Integer.valueOf(activityId));
				activityGoodsMapper.insertSelective(activityGoods);
			}

			// 商品信息发生变化 同步搜索条件
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("actionType", EventTag.GOODS_CHANGE);
			map.put("storeNo", storeNo);
			MQUtil.sendObMsg(map, jmsTemplate, topicDestination);

		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			e.printStackTrace();
			log.error(LogInfo.ERROR);
		}
		return result;
	}

	@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
	@Transactional(rollbackFor = { Exception.class })
	@Override
	public ResponseForm addMultiGoods(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if (param.getData() != null) {
			Map paramMap = (Map) param.getData();
			String storeNo = (String) paramMap.get("storeNo");
			paramMap.put("relation", String.valueOf(System.currentTimeMillis()));/* 同款不同色标识 */
			paramMap.put("soldonTime", new Date());/* 上架时间 */
			Integer styleCount = (Integer) paramMap.get("styleCount");/* 款式数量 */
			List styleList = (List) paramMap.get("paramList");/* 款式集合 */
			Map styleMap = new HashMap<>();/* 单个款式参数 */
			Object goodsPrice;/* 商品价格 */
			Object discountPrice;/* 折扣价格 */
			Object discountRate;/* 折扣率 */
			Object memberPrice;/* 会员价格 */
			Object memberRate;/* 会员折扣率 */
			try {
				for (int i = 0; i < styleCount; i++) {
//					Goods goods = MyBeanUtils.populate(new Goods(), paramMap);
					styleMap = (Map) styleList.get(i);
					/* 必要参数判空处理 */
					/* 价格格式处理 */
					goodsPrice = styleMap.get("goodsPrice");
					discountPrice = styleMap.get("discountPrice");
					discountRate = styleMap.get("discountRate");
					memberPrice = styleMap.get("memberPrice");
					memberRate = styleMap.get("memberRate");
					if (goodsPrice != null && goodsPrice != "") {
						styleMap.put("goodsPrice", new BigDecimal(goodsPrice.toString()));
					} else {
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						result.fail("400", "缺少必要参数");
						return result;
					}
					if (discountPrice != null && discountPrice != "" && discountRate != null && discountRate != "") {
						styleMap.put("discountPrice", new BigDecimal(discountPrice.toString()));
						styleMap.put("discountRate", new BigDecimal(discountRate.toString()));
					}
					if (memberPrice != null && memberPrice != "" && memberRate != null && memberRate != "") {
						styleMap.put("memberPrice", new BigDecimal(memberPrice.toString()));
						styleMap.put("memberRate", new BigDecimal(memberRate.toString()));
					}
					if (styleMap.get("goodsPic") == null || styleMap.get("goodsPic") == ""
							|| styleMap.get("goodsColor") == null || styleMap.get("goodsColor") == ""
							|| styleMap.get("goodsCode") == null || styleMap.get("goodsCode") == ""
							|| styleMap.get("goodsImg") == null || styleMap.get("goodsImg") == ""
							|| styleMap.get("goodsSize") == null || styleMap.get("goodsSize") == "") {
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						result.fail("400", "缺少必要参数");
						return result;
					}

					/* 基础信息添加 */
					Goods goods = MyBeanUtils.populate(new Goods(), styleMap);
					goodsMapper.insertSelective(goods);

					/* 活动商品信息添加 */
					ActivityGoods activityGoods = new ActivityGoods();
					activityGoods.setGoodsId(goods.getGoodsId());
					activityGoods.setActivityId(goods.getActivityId());
					activityGoodsMapper.insertSelective(activityGoods);

					/* 图片信息添加 */
					List goodsImages = (List) styleMap.get("goodsImg");
					for (Object objectUrl : goodsImages) {
						GoodsImage goodsImage = new GoodsImage();/* 图片参数 */
						goodsImage.setGoodsId(goods.getGoodsId());
						goodsImage.setUrl(objectUrl.toString());
						goodsImageMapper.insertSelective(goodsImage);
					}

					/* 规格库存信息添加 */
					List<Map> goodsSizes = (List<Map>) styleMap.get("goodsSize");
					for (Map stockMap : goodsSizes) {
						GoodsStock goodsStock = new GoodsStock(); /* 库存信息 */
						goodsStock.setGoodsId(goods.getGoodsId());
						goodsStock.setSpecsName((String) stockMap.get("size"));
						goodsStock.setStockNum((Integer) stockMap.get("num"));
						goodsStockMapper.insertSelective(goodsStock);
					}
				}
				// 商品信息发生变化 同步搜索条件
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("actionType", EventTag.GOODS_CHANGE);
				map.put("storeNo", storeNo);
				MQUtil.sendObMsg(map, jmsTemplate, topicDestination);
			} catch (Exception e) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				e.printStackTrace();
				log.error("数据库访问错误" + e);
				result.fail("400", "数据库访问错误");
			}
		} else {
			result.fail("400", "参数为空");
		}
		return result;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public ResponseForm updateGoods(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			String storeNo = (String) paramMap.get("storeNo");
			String goodsId = (String) paramMap.get("goodsId");
			String activityId = (String) paramMap.get("activityId");
			String memberPrice = (String) paramMap.get("memberPrice");
			String memberRate = (String) paramMap.get("memberRate");

			if (!StringUtils.isNotBlank(storeNo) || !StringUtils.isNotBlank(goodsId)
					|| !StringUtils.isNotBlank(activityId)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}
			// 原价
			String goodsPrice = (String) paramMap.get("goodsPrice");
			BigDecimal bd = new BigDecimal(goodsPrice);
			paramMap.put("goodsPrice", bd);
			// 折扣价
			String discountPrice = (String) paramMap.get("discountPrice");
			if (StringUtils.isNotBlank(discountPrice)) {
				BigDecimal discountbd = new BigDecimal(discountPrice);
				paramMap.put("discountPrice", discountbd);
			}
			// else{
			// paramMap.put("discountPrice", 0);
			// }
			// 会员价
			if (StringUtils.isNotBlank(memberPrice)) {
				paramMap.put("memberRate", new BigDecimal(memberRate));
				paramMap.put("memberPrice", new BigDecimal(memberPrice));
			}
			// 代购费
			String purchaseCost = (String) paramMap.get("purchaseCost");
			if (StringUtils.isNotBlank(purchaseCost)) {
				BigDecimal cost = new BigDecimal(purchaseCost);
				paramMap.put("purchaseCost", cost);
			} else {
				paramMap.put("purchaseCost", 0);
			}

			Goods goods = new Goods();
			MyBeanUtils.populate(goods, paramMap);
			// 修改图片信息
			List imgList = (List) paramMap.get("goodsImg");
			if (imgList != null && imgList.size() > 0) {
				GoodsImage gImg = new GoodsImage();
				gImg.setGoodsId(goods.getGoodsId());
				goodsImageMapper.delete(gImg);
				for (int j = 0; j < imgList.size(); j++) {
					gImg = new GoodsImage();
					gImg.setGoodsId(goods.getGoodsId());
					gImg.setUrl((String) imgList.get(j));
					gImg.setMediaType(0);
					goodsImageMapper.insertSelective(gImg);
				}
			}
			// 修改尺码信息
			List sizeList = (List) paramMap.get("goodsSize");
			if (sizeList != null && sizeList.size() > 0) {
				GoodsStock gStock = new GoodsStock();
				gStock.setGoodsId(goods.getGoodsId());
				goodsStockMapper.delete(gStock);
				for (int k = 0; k < sizeList.size(); k++) {
					Map<String, Object> stockMap = (Map<String, Object>) sizeList.get(k);
					gStock = new GoodsStock();
					gStock.setGoodsId(goods.getGoodsId());
					gStock.setSpecsName((String) stockMap.get("size"));
					String num = (String) stockMap.get("num");
					gStock.setStockNum(Integer.valueOf(num));
					goodsStockMapper.insertSelective(gStock);
				}
			}
			// 下架时间
			if (goods.getSoldout() != null && goods.getSoldout() == 1) {
				goods.setSoldoutTime(new Date());
			}
			// 修改活动信息
			// 商品关联活动
			ActivityGoods activityGoods = new ActivityGoods();
			activityGoods.setGoodsId(goods.getGoodsId());
			activityGoodsMapper.delete(activityGoods);

			activityGoods.setActivityId(Integer.valueOf(activityId));
			activityGoodsMapper.insertSelective(activityGoods);

			goodsMapper.updateByPrimaryKeySelective(goods);

			if (goods.getSoldout() == 1) {
				// 商品信息发生变化 同步搜索条件
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("actionType", EventTag.GOODS_CHANGE);
				map.put("storeNo", storeNo);
				MQUtil.sendObMsg(map, jmsTemplate, topicDestination);
			}

		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			e.printStackTrace();
			log.error(LogInfo.ERROR);
		}
		return result;
	}


	@Transactional(rollbackFor = Exception.class)
	@SuppressWarnings({ "unused", "unchecked", "rawtypes" })
	@Override
	public ResponseForm updateRelationGoods(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if (param.getData() != null) {
			Map paramMap = (Map) param.getData();
			String storeNo = (String) paramMap.get("storeNo");
			List<Map> styleList = (List<Map>) paramMap.get("paramList");/* 款式集合 */
			Object goodsPrice;/* 商品价格 */
			Object discountPrice;/* 折扣价格 */
			Object discountRate;/* 折扣率 */
			Object memberPrice;/* 会员价格 */
			Object memberRate;/* 会员折扣率 */
			try {
				if (paramMap.get("relation") == null || paramMap.get("relation") == ""
						|| paramMap.get("paramList") == null || paramMap.get("paramList") == "") {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					result.fail("400", "缺少必要参数");
					return result;
				}
				/*更新商品公共信息*/
				if(paramMap.get("presaleTime")!=null&&paramMap.get("presaleTime")!="") {
					paramMap.put("presaleTime", DateUtil.toDate(paramMap.get("presaleTime")));
				}
				goodsMapper.updateGoodsByRelationOrGoodsId(paramMap);
				/*更新活动商品关联*/
				if(StringUtils.isNotBlank((String) paramMap.get("activityId"))) {
					activityGoodsMapper.updateByRelation(paramMap);
				}
				for (Map goodsMap : styleList) {
					/*单独更新单个商品的非公共信息*/
					/* 价格格式处理 */
					goodsPrice = goodsMap.get("goodsPrice");
					discountPrice = goodsMap.get("discountPrice");
					discountRate = goodsMap.get("discountRate");
					memberPrice = goodsMap.get("memberPrice");
					memberRate = goodsMap.get("memberRate");
					if (goodsPrice != null && goodsPrice != "") {
						goodsMap.put("goodsPrice", new BigDecimal(goodsPrice.toString()));
					}
					if (discountPrice != null && discountPrice != "" && discountRate != null && discountRate != "") {
						goodsMap.put("discountPrice", new BigDecimal(discountPrice.toString()));
						goodsMap.put("discountRate", new BigDecimal(discountRate.toString()));
					}
					if (memberPrice != null && memberPrice != "" && memberRate != null && memberRate != "") {
						goodsMap.put("memberPrice", new BigDecimal(memberPrice.toString()));
						if (StringUtils.isNotBlank((String) memberRate)) {
							goodsMap.put("memberRate", new BigDecimal(memberRate.toString()));
						} else {
							goodsMap.remove("memberRate");
						}
					}
					if((Integer)goodsMap.get("soldout")==1) {
						goodsMap.put("soldoutTime", new Date());
					}
					goodsMapper.updateGoodsByRelationOrGoodsId(goodsMap);

					/*图片更新 先删除再添加*/
					GoodsImage gImg = new GoodsImage();
					gImg.setGoodsId((Integer) goodsMap.get("goodsId"));
					goodsImageMapper.delete(gImg);
					List goodsImgs = (List) goodsMap.get("goodsImg");
					for (Object url: goodsImgs) {
						gImg = new GoodsImage();
						gImg.setGoodsId((Integer) goodsMap.get("goodsId"));
						gImg.setUrl((String)url);
						gImg.setMediaType(0);
						goodsImageMapper.insertSelective(gImg);
					}

					/*规格和库存信息更新 先删除再添加*/
					GoodsStock gStock = new GoodsStock();
					gStock.setGoodsId((Integer) goodsMap.get("goodsId"));
					goodsStockMapper.delete(gStock);
					List<Map> sizeList = (List) goodsMap.get("goodsSize");
					for (Map styleMap : sizeList) {
						gStock = new GoodsStock();
						gStock.setGoodsId((Integer) goodsMap.get("goodsId"));
						gStock.setSpecsName((String) styleMap.get("size"));
						gStock.setStockNum((Integer)styleMap.get("num"));
						goodsStockMapper.insertSelective(gStock);
					}
				}
//				if (goods.getSoldout() == 1) {
//					// 商品信息发生变化 同步搜索条件
//					Map<String, Object> map = new HashMap<String, Object>();
//					map.put("actionType", EventTag.GOODS_CHANGE);
//					map.put("storeNo", storeNo);
//					MQUtil.sendObMsg(map, jmsTemplate, topicDestination);
//				}
			} catch (Exception e) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				e.printStackTrace();
				log.error("数据库访问错误" + e);
				result.fail("400", "数据库访问错误");
			}
		} else {
			result.fail("400", "参数为空");
		}
		return result;
	}

	@Override
	public ResponseForm searcheGoods(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			String storeNo = (String) paramMap.get("storeNo");
			if (!StringUtils.isNotBlank(storeNo)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}
			com.purchase.util.Page.parsePage(paramMap);
			Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
			List<Map<String, Object>> list = goodsMapper.searcheGoodsList(paramMap);
			;
			result.setData(list);
			result.setTotal((int) pageHelper.getTotal());
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			e.printStackTrace();
			log.error(LogInfo.ERROR);
		}
		return result;

	}

	@SuppressWarnings("unchecked")
	@Override
	public ResponseForm getHotGoods(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if (param.getData() != null) {
			Map paramMap = (Map) param.getData();
			paramMap.get("wxUid");
			paramMap.put("startTime", DateUtil.toDate(paramMap.get("startTime")));
			paramMap.put("endTime", DateUtil.toDate(paramMap.get("endTime")));
			try {
				List goodsMap = goodsMapper.getHotGoods(paramMap);
				result.succ("操作成功", goodsMap);
			} catch (Exception e) {
				result.fail("400", "参数错误");
				e.printStackTrace();
				log.error(LogInfo.ERROR);
			}
		} else {
			result.fail("400", "参数错误");
		}
		return result;
	}

	@Override
	public ResponseForm editGoodsByPc(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if (param.getData() != null) {
			Map paramMap = (Map) param.getData();
			if (paramMap.get("memberPrice") != null || paramMap.get("discountPrice") != null
					|| paramMap.get("goodsPrice") != null || paramMap.get("soldout") != null) {
				goodsMapper.editGoodsByPc(paramMap);
			}
			result.succ("更新商品信息成功");
		} else {
			result.fail("400", "无更新信息");
		}
		return result;
	}

}
